//
//  CommentViewController.m
//  XDCommonApp
//
//  Created by xindaoapp on 14-3-11.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "CommentViewController.h"
#import "XDTools.h"
#import "XDHeader.h"
#import "MostDetailViewController.h"

#define dNaviTitle                                     @"写评论"
#define kStrBegin                                      @""
#define kStrEnd                                         @"字"

#define dTagCommentTextView             1000
#define dTagToolBar                                 1001
#define dtextViewBtn                                1002//文本里边按钮
#define dLengthComment                        140     //最长可输入100字

#define dErrorInputInsufficient                 @"请输入评论内容"

@interface CommentViewController ()

{
    UIButton *numberOfWords;
    int _textLength;
    UILabel *uilabel;
}

@end

@implementation CommentViewController

@synthesize uID,workID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self initWidget];
}

- (void)initWidget{

    self.titleLabel.text = self.navTitle;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    self.titleLabel.textColor = TEXTBLACKCOLORE;
    
    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(266.0f,0,44 , 44);
//    [rightBtn setImage:[UIImage imageNamed:@"hotPoint_data"] forState:UIControlStateNormal];
    [rightBtn setTitle:@"发表" forState:UIControlStateNormal];
    [rightBtn setTitleColor:TEXTBLACKCOLORE forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(commitComment:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:rightBtn];
    
    commentTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 20, 320, 210)];
    commentTextView.backgroundColor = [UIColor whiteColor];
    commentTextView.font = [UIFont systemFontOfSize:14];
    commentTextView.keyboardType = UIKeyboardTypeDefault;
    commentTextView.delegate = self;
//    commentTextView.layer.cornerRadius = 10.0;
//    [commentTextView becomeFirstResponder];

    [self.contentView addSubview:commentTextView];
    uilabel = [[UILabel alloc]init];
    uilabel.frame =CGRectMake(10, 5, 200,20);
    uilabel.text = @"感觉如何？留几句言吧";
    uilabel.textColor =TEXTBLACKCOLORE4;
    uilabel.font = [UIFont systemFontOfSize:14];
    uilabel.enabled = NO;//lable必须设置为不可用
    uilabel.backgroundColor = [UIColor clearColor];
    [commentTextView addSubview:uilabel];
    
    //作用1.textView里边剩余字数 //作用2.使用按钮是为了添加删除全部文本功能
    numberOfWords = [UIButton buttonWithType:UIButtonTypeCustom];
    numberOfWords.frame = CGRectMake(commentTextView.frame.size.width-65, commentTextView.frame.size.height-25, 60.0f, 20.0f);
    numberOfWords.tag=dtextViewBtn;
    numberOfWords.titleLabel.font=[UIFont systemFontOfSize:15];
    numberOfWords.titleLabel.textColor = TEXTBLACKCOLORE;
    _textLength=140;
    NSString *remainingWords=[NSString stringWithFormat:@"%@%d%@",kStrBegin,_textLength,kStrEnd];
    [numberOfWords setTitle:remainingWords forState:UIControlStateNormal];
    [commentTextView addSubview:numberOfWords];
    
     _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(commentToMore:) userInfo:nil repeats:YES];

    
//    UITextView * tv = [[UITextView alloc] initWithFrame:CGRectMake(10, 50, 300, 300)];
//    tv.backgroundColor = [UIColor orangeColor];
//    tv.delegate = self;
//    [self.contentView addSubview:tv];
}

//每秒调用一次,计算长度
-(void)commentToMore:(id)sender
{
    _textLength = commentTextView.text.length;
    _textLength  = dLengthComment-_textLength;
    NSString *remainingWords = [NSString stringWithFormat:@"%@%d%@",kStrBegin,_textLength,kStrEnd];
    [numberOfWords setTitle:remainingWords forState:UIControlStateNormal];
    
    //剩余字数不大于0时候,取textView得前dLengthComment(100)个字符
    if(_textLength<=0)
    {
        NSString *str =[commentTextView.text substringToIndex:140];
        [commentTextView setText:str];
    }
}

- (void)commitComment:(id)sender
{

    if ([commentTextView.text  length] <= 0) {
//        [NKTools toastNotification:dErrorInputInsufficient andView:self.view andLoading:NO andIsBottom:NO];
        [XDTools showTips:dErrorInputInsufficient toView:self.contentView];
        
    }else{
//        [self sendComment];
        [self getXmlData:commentTextView.text];
    }

}
//-(void)textViewDidChange:(UITextView *)textView
//{
//    commentTextView.text =  textView.text;
//    if (textView.text.length == 0) {
//        uilabel.text = @"感觉如何？留几句言吧";
//    }else{
//        uilabel.text = @"";
//    }
//}
- (void)textViewDidBeginEditing:(UITextView *)textView{
    uilabel.text = @"";
}

- (void)textViewDidEndEditing:(UITextView *)textView{


}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [commentTextView resignFirstResponder];
}
#pragma mark  -------- DataSouceManager------------

- (void)getXmlData:(NSString *)_comStr
{
    uID = @"1000";
    DDLOG(@"uID = %@ workID = %@  com  = %@",uID,workID,_comStr);
    
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <AddCom xmlns=\"http://tempuri.org/\">"
                          "<comtxt>%@</comtxt>"
                          "<picid>%@</picid>"
                          "<uid>%@</uid>"
                          "</AddCom>",_comStr,workID,uID];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:ADDCOM];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    DDLOG(@"res = %@",responseDict);
                    
                    [XDTools showTips:@"评论成功" toView:self.contentView];
                    
                    [self refreshComm];
                    [self.navigationController popViewControllerAnimated:YES];
                   
//                    [[NSNotificationCenter defaultCenter] postNotificationName:@"postData" object:nil];
                    
                }else{
                    [XDTools showTips:@"评论失败" toView:self.contentView];
                }
            }
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
    
}

-(void)refreshComm{
    [self.mVC getXmlData];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
